package com.psytech.commons.configuration;

import java.io.File;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.lang.UnhandledException;

public final class ConfigurationLoader {

	private static final String CONFIG_FILE_KEY = "configFile.properties";

	private static ExtendedPropertiesConfiguration CONFIG;//NOPMD

	/**
	 * Retourne un ExtendedPropertiesConfiguration préconfiguré en fonction du
	 * nom du package de la méthode appellante
	 * 
	 * @return ExtendedPropertiesConfiguration
	 * @throws ConfigurationException
	 */
	public static ExtendedPropertiesConfiguration load() throws ConfigurationException {
		if (CONFIG == null) {
			Class mainClass = null;// NOPMD
			try {
				mainClass = Class.forName(new Throwable().getStackTrace()[1].getClassName());// NOPMD
			} catch (Exception exception) {
				throw new UnhandledException("Impossible de déterminer la classe principale de l'application", exception);
			}
			final String packageName = mainClass.getPackage().getName();
			File configFile = null;
			final String filepath = "./" + packageName + "." + CONFIG_FILE_KEY;
			configFile = new File(filepath);
			if (configFile.isFile()) {
				CONFIG = new ExtendedPropertiesConfiguration(configFile);
			} else {
				throw new IllegalStateException("Fichier de configuration " + filepath + " introuvable");
			}
		}
		return CONFIG;
	}

}
